// index.ts
// 格式化时间
function formatTime(timestamp: number): string {
  const date = new Date(timestamp);
  const year = date.getFullYear();
  const month = date.getMonth() + 1;
  const day = date.getDate();
  const hour = date.getHours();
  const minute = date.getMinutes();
  
  return `${year}-${month < 10 ? '0' + month : month}-${day < 10 ? '0' + day : day} ${hour < 10 ? '0' + hour : hour}:${minute < 10 ? '0' + minute : minute}`;
}

// 生成唯一ID的函数
function generateUUID(): string {
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
    const r = Math.random() * 16 | 0,
      v = c === 'x' ? r : (r & 0x3 | 0x8);
    return v.toString(16);
  });
}

// 获取用户ID，如果不存在则创建
function getUserId(): string {
  let userId = wx.getStorageSync('userId');
  if (!userId) {
    userId = generateUUID();
    wx.setStorageSync('userId', userId);
  }
  return userId;
}

Page({
  data: {
    posts: []
  },

  onLoad() {
    // 确保用户ID存在
    getUserId();
    
    // 加载帖子列表
    this.loadPosts();
  },

  onShow() {
    // 每次显示页面时刷新帖子列表
    this.loadPosts();
  },

  loadPosts() {
    // 获取所有帖子
    let posts = wx.getStorageSync('posts') || [];
    
    // 格式化时间
    posts = posts.map((post: any) => {
      return {
        ...post,
        formattedTime: formatTime(post.createTime)
      };
    });
    
    this.setData({ posts });
  },

  goToDetail(e: any) {
    const postId = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/detail/detail?id=${postId}`
    });
  },

  goToPost() {
    wx.switchTab({
      url: '/pages/post/post'
    });
  },

  refreshPosts() {
    wx.showLoading({
      title: '刷新中...'
    });
    
    setTimeout(() => {
      this.loadPosts();
      wx.hideLoading();
      
      wx.showToast({
        title: '刷新成功',
        icon: 'success'
      });
    }, 500);
  }
});